package com.itheima.task;

import com.itheima.common.constant.RedisConstant;
import com.itheima.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Set;

@Component
@Slf4j
public class imgCleanTask {  //定时任务
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AliOssUtil aliOssUtil;

//    @Scheduled(cron = "0 30 23 * * ?")  //每天晚上23:30触发
    @Scheduled(cron = "59 * * * * ?")  //表示每30秒 执行任务
    public void executeTask(){
        log.info("定时任务现在{}开始执行", LocalDateTime.now());
        if (redisTemplate.opsForSet().members(RedisConstant.SETMEAL_PIC_RESOURCES).isEmpty()){
            log.info("redis中没有图片产生，不用清理");
            return;
        }
        //计算redis中两个set集合的差集，即垃圾图片的集合
        Set<String> picNameSet = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);

        //清理阿里云上的图片
        picNameSet.forEach(picName->{
            String name=picName.substring(picName.lastIndexOf("/")+1);
            aliOssUtil.delete(name);
        });
        //清除缓存
        redisTemplate.delete(RedisConstant.SETMEAL_PIC_DB_RESOURCES);
        redisTemplate.delete(RedisConstant.SETMEAL_PIC_RESOURCES);
        log.info("清理成功");
    }
}
